package cn.zhutmj_bigmarket.domain.strategy.service.armory;

import cn.zhutmj_bigmarket.domain.strategy.model.entity.StrategyAwardEntity;
import cn.zhutmj_bigmarket.domain.strategy.model.entity.StrategyEntity;
import cn.zhutmj_bigmarket.domain.strategy.model.entity.StrategyRuleEntity;
import cn.zhutmj_bigmarket.domain.strategy.repository.IStrategyRepository;
import cn.zhutmj_bigmarket.types.enums.ResponseCode;
import cn.zhutmj_bigmarket.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * @description
 * @author: zhutmj
 * @createTime: 2025/6/3022:58
 */
@Slf4j
@Service
public class StrategyArmoryDispatch implements IStrategyArmory,IStrategyDispatch{

    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        // 1.查询概率配置,也就是每个策略包含的奖品
        List<StrategyAwardEntity> awardList = strategyRepository.queryStrategyAwardList(strategyId);

        // 2. 权重策略配置--适用于 rule_weight 权重规则配置
        StrategyEntity strategy = strategyRepository.queryStrategyEntityByStrategyId(strategyId);
        // 首先就是获取一下这个策略的策略权重（如果配了权重策略的话）
        String weightRuleStrategy = strategy.getStrategyWeight();
        if(null == weightRuleStrategy) return true;

        // 查询一下策略规则
        StrategyRuleEntity strategyRule = strategyRepository.queryStrategyRule(strategyId, strategy.getRuleModels());
        if( null == strategyRule) {
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        // 权重策略下不同
        Map<String, List<Integer>> listMap = strategyRule.getRuleWeightValues();
        Set<String> keys = listMap.keySet();
        for(String key : keys){
            // 权重策略下的奖品需要根据不同权重进行装配
            List<Integer> values = listMap.get(key);
            // 筛选出该策略下满足权重的奖品进行装配
            ArrayList<StrategyAwardEntity> strategyAwardList = new ArrayList<>(awardList);
            strategyAwardList.removeIf(strategyAwardEntity -> !values.contains(strategyAwardEntity.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key), strategyAwardList);
        }
        return true;
    }

    private void assembleLotteryStrategy(String key, List<StrategyAwardEntity> awardList) {
        // 1.获取最小概率值
        BigDecimal minAward = awardList.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        // 2.获取概率总和
        BigDecimal sumAward = awardList.stream().map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO,BigDecimal::add);

        // 3.用 1 % 0.0001 获得概率范围，百分位、千分位、万分位
        BigDecimal rateRange = sumAward.divide(minAward,0, RoundingMode.CEILING);

        // 4.生成一个抽奖奖品概率查找表
        List<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        for(StrategyAwardEntity strategyAwardEntity:awardList){
            Integer awardId = strategyAwardEntity.getAwardId();
            BigDecimal rate = strategyAwardEntity.getAwardRate();
            // 计算每个概率值对应最小概率的数量，也就是需要放进查找表的奖品数，循环填充
            for(int i=0;i<rateRange.multiply(rate).setScale(0, RoundingMode.CEILING).intValue();i++){
                strategyAwardSearchRateTables.add(awardId);
            }
        }

        // 5. 对存储的奖品进行乱序操作
        Collections.shuffle(strategyAwardSearchRateTables);

        // 6.生成出Map集合，key值，对应的就是后续的概率值。通过概率来获得对应的奖品ID
        Map<Integer,Integer> shuffleStrategyAwardSearchRateTable = new LinkedHashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTable.put(i, strategyAwardSearchRateTables.get(i));
        }

        // 7. 存进redis
        strategyRepository.storeStrategyAwardSearchRateTable(key,shuffleStrategyAwardSearchRateTable.size(),shuffleStrategyAwardSearchRateTable);
    }

    @Override
    public Integer getRandomAwardId(Long strategyId) {
        String key = String.valueOf(strategyId);
        int rateRange = strategyRepository.getRateRange(key);
        return strategyRepository.getStrategyAwardAssemble(String.valueOf(strategyId),
                new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        int rateRange = strategyRepository.getRateRange(key);
        // 通过生成的随机值，获取概率值奖品查找表的结果
        return strategyRepository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));
    }


}
